package com.wbk.lotterysystemlotteryservice.service.serviceImpl;

import com.wbk.lotterysystemlotteryservice.commons.bo.PrizeBO;
import com.wbk.lotterysystemlotteryservice.entity.Prize;
import com.wbk.lotterysystemlotteryservice.entity.PrizeExample;
import com.wbk.lotterysystemlotteryservice.mapper.PrizeMapper;
import com.wbk.lotterysystemlotteryservice.service.PrizeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PrizeServiceImpl implements PrizeService {

    @Autowired
    PrizeMapper prizeMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public List<Prize> save(Integer lotteryId, List<PrizeBO> prizeBOList) {
        List<Prize> prizes = new ArrayList<>();
        for (PrizeBO prizeBO : prizeBOList) {
            Prize prize = new Prize();
            BeanUtils.copyProperties(prizeBO, prize);
            prize.setLotteryId(lotteryId);
            prizes.add(prize);
        }
        prizeMapper.insertList(prizes);
        return prizes;
    }

    @Cacheable(cacheNames = "prize::byLotteryId", key = "#lotteryId")
    @Override
    public List<Prize> getPrizeByLotteryId(Integer lotteryId) {
        PrizeExample prizeExample = new PrizeExample();
        PrizeExample.Criteria criteria = prizeExample.createCriteria();
        criteria.andLotteryIdEqualTo(lotteryId);
        return prizeMapper.selectByExample(prizeExample);
    }

    @CacheEvict(cacheNames = "prize::byLotteryId", key = "#lotteryId")
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public List<Prize> update(Integer lotteryId, List<PrizeBO> prizeBOList) {
        //先将该抽奖活动所对应的奖品全部删除
        PrizeExample prizeExample = new PrizeExample();
        PrizeExample.Criteria criteria = prizeExample.createCriteria();
        criteria.andLotteryIdEqualTo(lotteryId);
        prizeMapper.deleteByExample(prizeExample);

        //再批量插入新的奖品
        List<Prize> prizes = new ArrayList<>();
        for (PrizeBO prizeBO : prizeBOList) {
            Prize prize = new Prize();
            BeanUtils.copyProperties(prizeBO, prize);
            prize.setLotteryId(lotteryId);
            prizes.add(prize);
        }
        prizeMapper.insertList(prizes);
        return prizes;
    }

    @Cacheable(cacheNames = "prize::byId", key = "#id")
    @Override
    public Prize getPrizeById(Integer id) {
        return prizeMapper.selectByPrimaryKey(id);
    }
}
